/*
 * @Author: xuhua
 * @Date: 2023-09-13 15:11:48
 * @LastEditors: xuhua
 * @LastEditTime: 2023-09-19 13:54:52
 * @FilePath: /v3-element-admin/src/store/modules/user.ts
 * @Description:
 *
 */
import { store } from "@/store";
import { resetRouter } from "@/router";

import { loginApi, logoutApi } from "@/api/auth";
import { getUserInfo } from "@/api/user";
import { LoginData, LoginResult } from "@/api/auth/types";
import { UserInfo } from "@/api/user/types";

export const useUserStore = defineStore("user", () => {
	const token = useStorage("accessToken", "");
	const avatar = ref("");
	const nickname = ref("");
	const username = ref("");
	const userId = ref(0);
	const roles = ref<string[]>([]);
	const user: UserInfo = {
		roles: [],
		perms: [],
	};

	/**
	 * 登录调用
	 * @param {LoginData}
	 * @returns
	 */
	function login(loginData: LoginData) {
		return new Promise<LoginResult>((resolve, reject) => {
			loginApi(loginData)
				.then((response) => {
					console.log("file: user.ts:39 ~ .then ~ response:", response);
					const { tokenType, accessToken } = response.data;
					token.value = tokenType + " " + accessToken; // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
					localStorage.setItem("accessToken", token.value);
					resolve(response);
				})
				.catch((err) => {
					reject(err);
				});
		});
	}

	/**
	 * 获取用户信息(用户昵称、头像、角色集合、权限集合)
	 * @returns
	 */
	function getInfo() {
		return new Promise<UserInfo>((resolve, reject) => {
			getUserInfo()
				.then((response) => {
					const { data } = response;
					avatar.value = data.avatar || "";
					nickname.value = data.nickname || "";
					username.value = data.username || "";
					userId.value = data.userId || 0;
					user.roles = data.roles;
					user.perms = data.perms;
					roles.value = data.roles;
					resolve(response.data);
				})
				.catch((err) => {
					reject(err);
				});
		});
	}

	/**注销 */
	function logout() {
		return new Promise<void>((resolve, reject) => {
			// 退出登录,清空缓存,清空路由
			logoutApi()
				.then(() => {
					resetRouter();
					resetStore();
					location.reload();
					resolve();
				})
				.catch((err: any) => {
					reject(err);
				});
		});
	}

	/** 清空缓存 */
	function resetStore() {
		resetRouter();
		token.value = "";
		localStorage.clear();
		Object.assign(user, { roles: [], perms: [] });
	}

	return { user, roles, login, getInfo, logout, resetStore };
});

// 非setup
export function useUserStoreHook() {
	return useUserStore(store);
}
